package com.example.xunai.controller;

import com.example.xunai.service.user.AuthService;
import com.example.xunai.service.user.UserService;
import com.example.xunai.entity.User;
import com.example.xunai.entity.Admin;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.time.LocalDateTime;
import java.util.Optional;

@Controller
@RequestMapping("/auth")
public class AuthController {

    private final AuthService authService;
    private final UserService userService;

    public AuthController(AuthService authService, UserService userService) {
        this.authService = authService;
        this.userService = userService;
    }

    // ==================== 处理 /auth 路径下的根路径 ====================

    /**
     * 处理 /auth/ 路径
     */
    @GetMapping("/")
    public String authRoot() {
        return "redirect:/auth/login";
    }

    /**
     * 处理 /auth 路径（无斜杠）
     */
    @GetMapping("")
    public String authRootNoSlash() {
        return "redirect:/auth/login";
    }

    // ==================== 原有方法保持不变 ====================

    @GetMapping("/login")
    public String showLoginPage(Model model) {
        return "login";
    }

    @PostMapping("/login/user")
    public String loginUser(@RequestParam String username,
                            @RequestParam String password,
                            HttpSession session, Model model,
                            RedirectAttributes redirectAttributes) {
        Optional<User> user = authService.authenticateUser(username, password);
        if (user.isPresent()) {
            session.setAttribute("user", user.get());
            return "redirect:/auth/chat";
        } else {
            // 只在有错误时添加错误属性
            redirectAttributes.addFlashAttribute("error", "用户名或密码错误");
            return "redirect:/auth/login";
        }
    }

    @PostMapping("/login/admin")
    public String loginAdmin(@RequestParam String username,
                             @RequestParam String password,
                             HttpSession session, Model model,
                             RedirectAttributes redirectAttributes) {
        Optional<Admin> admin = authService.authenticateAdmin(username, password);
        if (admin.isPresent()) {
            session.setAttribute("admin", admin.get());
            return "redirect:/admin/dashboard";
        } else {
            redirectAttributes.addFlashAttribute("error", "管理员用户名或密码错误");
            return "redirect:/auth/login";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/auth/login";
    }

    @GetMapping("/register")
    public String showRegisterPage(Model model) {
        if (!model.containsAttribute("error")) {
            model.addAttribute("error", "");
        }
        return "user/register";
    }

    @PostMapping("/register")
    public String register(@RequestParam String username,
                           @RequestParam String email,
                           @RequestParam String phone,
                           @RequestParam String password,
                           @RequestParam String confirmPassword,
                           RedirectAttributes redirectAttributes) {

        try {
            // 验证数据
            if (!password.equals(confirmPassword)) {
                redirectAttributes.addFlashAttribute("error", "两次输入的密码不一致");
                return "redirect:/auth/register";
            }

            // 检查用户名是否已存在
            if (userService.existsByUsername(username)) {
                redirectAttributes.addFlashAttribute("error", "用户名已存在");
                return "redirect:/auth/register";
            }

            // 检查邮箱是否已存在
            if (userService.existsByEmail(email)) {
                redirectAttributes.addFlashAttribute("error", "邮箱已被注册");
                return "redirect:/auth/register";
            }

            // 检查手机号是否已存在
            if (phone != null && !phone.trim().isEmpty() && userService.existsByPhone(phone)) {
                redirectAttributes.addFlashAttribute("error", "手机号已被注册");
                return "redirect:/auth/register";
            }

            // 创建新用户
            User user = new User();
            user.setUsername(username);
            user.setEmail(email);
            user.setPhone(phone);
            user.setPassword(password);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());

            // 保存用户
            userService.saveUser(user);

            redirectAttributes.addFlashAttribute("success", "注册成功！请登录");
            return "redirect:/auth/login";

        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("error", "注册失败，请稍后重试");
            return "redirect:/auth/register";
        }
    }

    @GetMapping("/chat")
    public String chatPage(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/auth/login";
        }
        model.addAttribute("user", user);
        return "user/chat";
    }

}